package com.zhangzhan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangzhan.constants.SystemConstants;
import com.zhangzhan.domain.commcon.ResponseResult;
import com.zhangzhan.domain.dto.CategoryDto;
import com.zhangzhan.domain.dto.CategoryListDto;
import com.zhangzhan.domain.dto.SaveCategoryDto;
import com.zhangzhan.domain.entity.Article;
import com.zhangzhan.domain.entity.Category;
import com.zhangzhan.domain.vo.CategoryVO;
import com.zhangzhan.domain.vo.CategoryVOs;
import com.zhangzhan.domain.vo.PageVO;
import com.zhangzhan.mapper.CategoryMapper;
import com.zhangzhan.service.ArticleService;
import com.zhangzhan.service.CategoryService;
import com.zhangzhan.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2022-09-10 21:11:08
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    ArticleService articleService;

    /**
     * 查询分类
     *
     * @return
     */
    @Override
    public ResponseResult getCategoryList() {
        //查询文章信息
        LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Article> wrapper = articleWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //封装到list集合
        List<Article> articleList = articleService.list(wrapper);

        //根据stream流查询出文章对应的分类id，并用set去重
        Set<Long> categoryId = articleList.stream()
                .map(article -> article.getCategoryId()).collect(Collectors.toSet());

        //根据文章的分类id去对比分类id来查询出数据
        List<Category> categories = this.listByIds(categoryId);

        categories = categories.stream()
                .filter(category -> SystemConstants.ARTICLE_STATUS_STRING.equals(category.getStatus()))
                .collect(Collectors.toList());

        //copy 数据到vo
        List<CategoryVO> vo = BeanCopyUtils.beanCopyUtil(categories, CategoryVO.class);

        //返回数据
        return ResponseResult.okResult(vo);
    }

    /**
     * @return com.zhangzhan.domain.commcon.ResponseResult<com.zhangzhan.domain.vo.CategoryVO>
     * @description 查所有
     * @author 31115
     * @date 2022/12/6 16:04
     */
    @Override
    public ResponseResult<CategoryVOs> listAllCategory() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getDelFlag, "0");
        List<Category> list = list(wrapper);
        List<CategoryVOs> categoryVOs = list.stream()
                .map(category -> {
                    CategoryVOs vo = new CategoryVOs();
                    vo.setId(category.getId());
                    vo.setDescription(category.getDescription());
                    vo.setName(category.getName());
                    return vo;
                }).collect(Collectors.toList());
        return ResponseResult.okResult(categoryVOs);
    }

    /**
     * @param pageNum
     * @param pageSize
     * @param dto
     * @return com.zhangzhan.domain.commcon.ResponseResult<com.zhangzhan.domain.vo.PageVO>
     * @description 分页查询
     * @author 31115
     * @date 2022/12/8 16:31
     */
    @Override
    public ResponseResult<PageVO> pageList(Integer pageNum, Integer pageSize, CategoryListDto dto) {

        Page<Category> categoryPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getName()), Category::getName, dto.getName())
                .eq(StringUtils.hasText(dto.getStatus()), Category::getStatus, dto.getStatus());

        page(categoryPage, wrapper);
        List<Category> records = categoryPage.getRecords();
        List<CategoryDto> categoryDtos = BeanCopyUtils.beanCopyUtil(records, CategoryDto.class);

        return ResponseResult.okResult(new PageVO(categoryDtos, categoryPage.getTotal()));
    }

    /**
     * @param dto
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 新增分类
     * @author 31115
     * @date 2022/12/8 16:41
     */
    @Override
    public ResponseResult saveCategory(SaveCategoryDto dto) {

        if (!StringUtils.hasText(dto.getName())) {
            return ResponseResult.errorResult(500, "分类姓名不能为空");
        }

        if (hasCategoryName(dto.getName())) {
            return ResponseResult.errorResult(500, "分类名称不能重复");
        }

        Category category = BeanCopyUtils.beanCopyUtils(dto, Category.class);
        save(category);

        log.info("新增分类成功！");

        return ResponseResult.okResult();
    }


    private boolean hasCategoryName(String name) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, name);
        int count = count(wrapper);
        return count > 0;
    }

    /**
     * @param
     * @return
     * @description 修改前回显
     * @author 31115
     * @date 2022/12/8 16:53
     */
    @Override
    public ResponseResult<CategoryDto> selectById(Long id) {
        if (id >= 0) {
            Category category = getById(id);
            CategoryDto categoryDto = BeanCopyUtils.beanCopyUtils(category, CategoryDto.class);
            return ResponseResult.okResult(categoryDto);
        } else {
            return ResponseResult.errorResult(500, "id不合法");
        }
    }

    /**
     * @param dto
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 修改
     * @author 31115
     * @date 2022/12/8 16:59
     */
    @Override
    public ResponseResult updateCategory(CategoryDto dto) {
        if (!StringUtils.hasText(dto.getName())) {
            return ResponseResult.errorResult(500, "分类姓名不能为空");
        }
        Category category = BeanCopyUtils.beanCopyUtils(dto, Category.class);
        updateById(category);

        return ResponseResult.okResult();
    }

    /**
     * @param ids
     * @return com.zhangzhan.domain.commcon.ResponseResult
     * @description 删除
     * @author 31115
     * @date 2022/12/8 17:03
     */
    @Override
    public ResponseResult deleteCategory(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        Category category = new Category();
        for (Long id : idList) {
            if (id >= 0) {
                LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Category::getId,id)
                        .set(Category::getDelFlag,"1");
                update(category,wrapper);
            } else {
                return ResponseResult.errorResult(500, "id不合法");
            }
        }
        return ResponseResult.okResult();
    }
}

